package com.btpn.custody.security.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.btpn.custody.common.Constant;
import com.btpn.custody.dao.IArea;
import com.btpn.custody.dao.IGroupRole;
import com.btpn.custody.dao.ITL_GLOBAL;
import com.btpn.custody.dao.IUser;
import com.btpn.custody.entity.TL_GLOBAL;
import com.btpn.custody.entity.User;
import com.btpn.custody.security.model.UserModel;

/*
 * Pisahkan UserDetailsService dan IUserService
 */
@Service("userService")
@Transactional
public class UserServiceHibernate implements IUserService {

	@Autowired
	private IArea areaDaoHibernate;
	
	@Autowired
	private IGroupRole groupRoleDaoHibernate;
	
	@Autowired
	private IUser userDaoHibernate;

	@Autowired
	private ITL_GLOBAL TL_GLOBAL_DaoHibernate;
	
//	private PasswordEncoder encoder = new ShaPasswordEncoder(256);
	
//	@Override
//	@Transactional(readOnly=true)
//	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//		User user = (User) userDaoHibernate.get(username);
//		
//		if (user == null) {
//			throw new UsernameNotFoundException("Could not find a user named: " + username);
//		}		
//		
//		return user;
//	}

	@Override
	public void deleteUser(String username, String user) {
				
		userDaoHibernate.delete(userDaoHibernate.get(username));
		
		TL_GLOBAL_DaoHibernate.create(User.class.getName(), Constant.ACTION__DELETE, TL_GLOBAL.GROUP_3, user, "ID:" + username);
	}

	@Override
	@Transactional(readOnly=true)
	public List<UserModel> listUserModel() throws Exception {
		try {
			List<User> users = userDaoHibernate.findAll();
			
			List<UserModel> userModels;
			if (users.size()!=0) {
				userModels = new ArrayList<UserModel>();
				
				for (User user : users) {

					UserModel userModel = new UserModel();
					userModel.setUsername(user.getUsername());
					userModel.setEmail(StringUtils.trimToEmpty(user.getEmail()));		
					if (user.getArea() == null) userModel.setAreaName("");
					else userModel.setAreaName(StringUtils.defaultString(user.getArea().getName()));
					if (user.getGroupRole() == null) userModel.setAuth("");
					else userModel.setAuth(user.getGroupRole().toString());
					userModel.setEnable(user.isEnabled());
					
					userModels.add(userModel);
				}
				return userModels;
			} else return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void createOrUpdateUser(String username, String password, String email, Long areaId, Boolean enabled, Long groupRole, String user) {

		User theUser = userDaoHibernate.get(username);
		if (theUser == null) {
			theUser = new User();
			theUser.setUsername(username);
			// password set to default
//			theUser.setPassword(encoder.encodePassword(Constant.DEFAULT_PASSWORD, null));
			theUser.setEmail(email);
			theUser.setArea(areaDaoHibernate.get(areaId));
			theUser.setEnabled(enabled);
			theUser.setGroupRole(groupRoleDaoHibernate.get(groupRole));
			theUser.setCreatedBy(user);
			Serializable id = userDaoHibernate.create(theUser);
			
			TL_GLOBAL_DaoHibernate.create(User.class.getName(), Constant.ACTION__CREATE, TL_GLOBAL.GROUP_3, user, "ID:" + id);
		} else {
			Long oldArea = 0L;
			if (theUser.getArea()!=null) oldArea = theUser.getArea().getId();
			
			Boolean oldEnabled = theUser.isEnabled();
			Long oldRoles = 0L;
			if (theUser.getGroupRole()!=null) theUser.getGroupRole().getId();
			
			// when update, username ga di-set untuk menghindari kemungkinan error duplicate (karena username is unique)
			// user juga tidak diupdate
//			theUser.setPassword(encoder.encodePassword(password, null));
			theUser.setEmail(email);
			theUser.setArea(areaDaoHibernate.get(areaId));
			theUser.setEnabled(enabled);
			theUser.setGroupRole(groupRoleDaoHibernate.get(groupRole));
			theUser.setUpdatedDate(new Date());
			theUser.setUpdatedBy(user);
	
			Long nowArea = 0L;
			if (theUser.getArea()!=null) nowArea = theUser.getArea().getId();
			
			Long nowRoles = 0L;
			if (theUser.getGroupRole()!=null) theUser.getGroupRole().getId();
			
			TL_GLOBAL_DaoHibernate.create(User.class.getName(), Constant.ACTION__UPDATE, TL_GLOBAL.GROUP_3, user, 
					"ID:" + theUser.getUsername() + 
					" Area:" + oldArea + Constant.ARROW_RIGHT + nowArea + 
					" Enabled:" + oldEnabled + Constant.ARROW_RIGHT + theUser.isEnabled() + 
					" Authorities:" + oldRoles + Constant.ARROW_RIGHT + nowRoles);
		}		
	}

//	@Override
//	public String resetPassword(String username) {
//		
//		User user = (User) userDaoHibernate.get(username);
//		user.setPassword(encoder.encodePassword(Constant.DEFAULT_PASSWORD, null));
//		user.setFirstLogin(true);
//
//		return "Success reset password";
//	}

//	@Override
//	public String changePassword(String oldPassword, String newPassword) {
//		
//		User user = userDaoHibernate.get(SecurityContextHolder.getContext().getAuthentication().getName());
//		
//		// validate old passwprd
//		if (!encoder.encodePassword(oldPassword, null).equals(user.getPassword())) {
//			return "Invalid old password";
//		}
//		user.setPassword(encoder.encodePassword(newPassword, null));
//		user.setFirstLogin(false);
//		
//		return "Success change password";
//	}
}
